package promote.brozen.netty.jav.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author Brozen
 * @date 2020/9/27 8:11 AM
 * @email brozen@qq.com
 */
public class NioServer {

    public static void main(String[] args) throws IOException {
        new NioServer().start();
    }

    public void start() throws IOException {
        // 1. 打开服务端通道
        ServerSocketChannel serverChannel = ServerSocketChannel.open();

        // 2. 绑定端口，设置非阻塞
        ServerSocket serverSocket = serverChannel.socket();
        serverSocket.bind(new InetSocketAddress("127.0.0.1", 8090));
        serverChannel.configureBlocking(false);

        Selector selector = Selector.open();
        ExecutorService bossGroup = Executors.newSingleThreadExecutor();
        ExecutorService workerGroup = Executors.newFixedThreadPool(2);

        SelectorReactor bossTask = new NioServerReactor(selector);
        bossTask.register(serverChannel, SelectionKey.OP_ACCEPT);
        bossGroup.execute(bossTask);
    }

}
